package com.atguigu.redis;

import redis.clients.jedis.*;

import java.util.HashSet;
import java.util.Set;

public class RedisUtil {


    public static void main(String[] args) {
     //   Jedis jedis = new Jedis("hdp1", 6379);
      //  Jedis jedis= RedisUtil.getJedisFromPool();
        JedisCluster jedis = RedisUtil.jedisCluster;
        jedis.set("k6666","v6666");
        String value = jedis.get("k6666");
        System.out.println(value);
        Set<Tuple> tuples = jedis.zrevrangeWithScores("article:visit",0,9);
        for (Tuple tuple : tuples) {
            System.out.println(tuple);
        }
        jedis.close();  //如果是jediscluster  close就意味着销毁整个连接池 之后就无法使用了 // 非集群 close=归还

    }

    static JedisPool jedisPool=null ;

    static JedisSentinelPool jedisSentinelPool= null;  // createJedisSentinelPool();

    static JedisCluster jedisCluster=createJedisCluster();

    static JedisCluster createJedisCluster(){
        HashSet<HostAndPort> hostAndPorts = new HashSet<>();
        hostAndPorts.add(new HostAndPort("hdp1",6381));
        hostAndPorts.add(new HostAndPort("hdp1",6389));

        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxTotal(10);//web应用200-1000  实时计算// 2-16
        jedisPoolConfig.setMaxIdle(5);
        jedisPoolConfig.setMinIdle(5);
        jedisPoolConfig.setBlockWhenExhausted(true);
        jedisPoolConfig.setMaxWaitMillis(5000);
        jedisPoolConfig.setTestOnBorrow(true);

        JedisCluster jedisCluster = new JedisCluster(hostAndPorts, jedisPoolConfig);
        return jedisCluster;

    }


    public static JedisSentinelPool createJedisSentinelPool(){

        Set<String> sentinels = new HashSet<>();
        sentinels.add("hdp1:26379");

        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxTotal(10);//web应用200-1000  实时计算// 2-16
        jedisPoolConfig.setMaxIdle(5);
        jedisPoolConfig.setMinIdle(5);
        jedisPoolConfig.setBlockWhenExhausted(true);
        jedisPoolConfig.setMaxWaitMillis(5000);
        jedisPoolConfig.setTestOnBorrow(true);


        JedisSentinelPool sentinelPool = new JedisSentinelPool("mymaster", sentinels, jedisPoolConfig);
        return  sentinelPool;
    }


    public static JedisPool createPool(){
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxTotal(10);//web应用200-1000  实时计算// 2-16
        jedisPoolConfig.setMaxIdle(5);
        jedisPoolConfig.setMinIdle(5);
        jedisPoolConfig.setBlockWhenExhausted(true);
        jedisPoolConfig.setMaxWaitMillis(5000);
        jedisPoolConfig.setTestOnBorrow(true);


        JedisPool jedisPool = new JedisPool(jedisPoolConfig, "hdp1", 6379);
        return  jedisPool;

    }

    public static   Jedis  getJedisFromPool(){
        return   jedisPool.getResource();

    }

    public static  Jedis getJedisFromSentinelPool(){
         return  jedisSentinelPool.getResource();
    }


}
